using System;
using System.Collections;
using System.IO;
using UnityEngine;

namespace PKGames.AssetLoader
{
	public class ReadTextureRequest : AssetRequest
	{
		public Action<Texture2D> OnSuccess;

		private string Tag => "[LoadTextureRequest] ";

		public Texture2D Texture
		{
			get;
			private set;
		}

		public ReadTextureRequest(string localPath, Action<Texture2D> onSuccess = null, Action onFailure = null)
		{
			_localPath = localPath;
			OnSuccess = (Action<Texture2D>)Delegate.Combine(OnSuccess, onSuccess);
			OnFailure = (Action)Delegate.Combine(OnFailure, onFailure);
		}

		public override IEnumerator Execute()
		{
			base.CurrentState = State.Executing;
			yield return MonoSingleton<AssetRequestManager>.Instance.StartCoroutine(ReadTexture(_localPath));
		}

		public override void Pause()
		{
		}

		public override void Resume()
		{
		}

		public override void Cancel()
		{
		}

		private IEnumerator ReadTexture(string localFilePath)
		{
			if (File.Exists(localFilePath))
			{
				WWW www = new WWW("file://" + localFilePath);
				try
				{
					yield return www;
					try
					{
						if (www.error == null)
						{
							Texture2D texture2D = new Texture2D(2, 2, TextureFormat.RGBA32, mipChain: false);
							www.LoadImageIntoTexture(texture2D);
							if (texture2D.height > 1)
							{
								texture2D.filterMode = FilterMode.Bilinear;
								Texture = texture2D;
								base.CurrentState = State.Successful;
								OnSuccess.Fire(texture2D);
							}
							else
							{
								base.CurrentState = State.Failed;
								OnFailure.Fire();
							}
						}
						else
						{
							UnityEngine.Debug.Log(Tag + "Error: Could not load " + localFilePath + ". " + www.error);
							base.CurrentState = State.Failed;
							OnFailure.Fire();
						}
					}
					catch (Exception ex)
					{
						UnityEngine.Debug.Log(Tag + "Error: Could not load " + localFilePath + ". " + ex.Message);
						base.CurrentState = State.Failed;
						OnFailure.Fire();
					}
					OnFinished.Fire(this);
				}
				finally
				{
					//base._003C_003E__Finally0();
				}
			}
		}

		private Texture2D ConvertToTexture(byte[] bytes)
		{
			try
			{
				Texture2D texture2D = new Texture2D(2, 2);
				texture2D.LoadImage(bytes);
				texture2D.filterMode = FilterMode.Bilinear;
				return texture2D;
			}
			catch (Exception ex)
			{
				UnityEngine.Debug.LogWarning(Tag + "Cant convert bytes to array: " + ex.ToString());
				return null;
			}
		}
	}
}
